﻿using System;
using System.Threading;
using Microsoft.Owin.Hosting;
using Topshelf;

namespace Aecg.OwinSelfHostServer.Service
{
    public class OwinSelfHostService : ServiceControl
    {
      
        private IDisposable _owinserver;


        /// <summary>
        /// 初始化OwinServer
        /// </summary>
        private void InitServer()
        {
            var baseAddress = "http://localhost:9000/";

            // Start OWIN host
            try
            {
                _owinserver = WebApp.Start<Startup>(baseAddress);
                Console.WriteLine($"当前挂载host:{baseAddress}");
                Console.ReadLine();
            }
            catch (Exception e)
            {

                Console.WriteLine("windows服务启动失败");
                Console.WriteLine(e.ToString());
            }

        }

        public bool Start(HostControl hostControl)
        {
           
            hostControl.RequestAdditionalTime(TimeSpan.FromSeconds(10));
            InitServer();
            return true;
        }

        public bool Stop(HostControl hostControl)
        {
            _owinserver.Dispose();
            Console.WriteLine("windows服务已停止");
            return true;
        }

        public bool Pause(HostControl hostControl)
        {
            _owinserver.Dispose();
            GC.Collect();
            Console.WriteLine("windows服务已暂停");
            return true;
        }

        public bool Continue(HostControl hostControl)
        {
            Thread.Sleep(1000*2);//延迟2s 防止暂停未gc server
            InitServer();
            Console.WriteLine("windows服务已继续");
            return true;
        }
    }
}